<?php
/**
 * P3 数据资源
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Http.php 1059 2011-11-18 09:26:15Z mmxie $
 */
class IG_Data_Source_Http extends IG_Data_Source
{
    private $_path;

    private $_body;

    public function run()
    {
        $params = $this->getParams();
        foreach ($params as $key => $val) {
            $this->_path = str_replace('{' . $key . '}', $val, $this->_path, $count);
            if ($count) {
                unset($params[$key]);
            }
        }

        if (!empty($params)) {
            $params = str_replace(array('=', '&'), array(':', '&p='),
                                  http_build_query($params));
            $this->_path .= strpos($this->_path, '?') === false ? '?p=' : '&p=';
            $this->_path .= $params;
        }

        if (strpos($this->_path, '{') !== false) {
            throw new IG_Exception("参数不正确($this->_path)");
        }
        $client  = new Zend_Http_Client($this->_path);

        $response = $client->request();

        if (!$response->isSuccessful())
            throw new IG_Exception('获取失败,返回状态: ' . $response->getStatus());

        $this->_body = Zend_Json::decode($response->getBody());
    }

    public function setPath($path)
    {
        $this->_path = $path;
        return $this;
    }

    public function getBody()
    {
        return $this->_body;
    }

    public function setBody($body)
    {
        $this->_body = $body;
        return $this;
    }
}